const model = require('../models/pollModel'),
  errCode = require('../../conf/errorCode'),
  wrap = require('../helper/wrap'),
  moment = require('moment'),
  conf = require('../../conf/const'),
  util = require('../helper/util'),
  _ = require('lodash'),
  {parseIntPageSize, checkContentValidate} = require('./commonService');

var getPollRelByPollId = (exports.getPollRelByPollId = function(
  pollId,
  callback,
) {
  model.getPollRelByPollId(pollId, callback);
});

var getPollByPostIdAndUid = (exports.getPollByPostIdAndUid = async function(
  postId,
  uid,
  callback,
) {
  var tmp = util.firstKeyOfNull(
    {
      postId,
    },
    ['postId'],
  );
  if (tmp != null) {
    return callback({
      errNo: errCode.LESS_OF_DATA_ERROR,
      extraMsgs: tmp,
    });
  }
  let _rel = await util.promiseify(model.getPollDetailByPostId)(postId);
  //文章下没有投票
  if (_rel.length <= 0) {
    return callback(null, null);
  }
  let pollDetail = _rel[0],
    pollId = pollDetail.pollId,
    rel = {};
  rel.title = pollDetail.question;
  rel.pollId = pollDetail.pollId;
  let pollRel = await util.promiseify(model.ifVotedByUid)(pollId, uid);
  if (pollRel.length > 0) {
    //未投票
    rel.voted = true;
    rel.voteRel = await util.promiseify(model.getPollRelByPollId)(pollId);
  } else {
    //投票
    rel.voted = false;
    rel.voteRel = null;
  }
  //判断有没有过期
  if (new Date(pollDetail.endAt).getTime() < Date.now()) {
    rel.status = '已过期';
  } else {
    rel.status = '未过期';
  }

  //获取选项
  let choiceRel = await util.promiseify(model.getPollChoiceByPollId)(pollId);
  rel.choiceArr = choiceRel;

  return callback(null, rel);
});

var getPollByPostId = (exports.getPollByPostId = async function(
  postId,
  callback,
) {
  var tmp = util.firstKeyOfNull(
    {
      postId,
    },
    ['postId'],
  );
  if (tmp != null) {
    return callback({
      errNo: errCode.LESS_OF_DATA_ERROR,
      extraMsgs: tmp,
    });
  }
  let _rel = await util.promiseify(model.getPollDetailByPostId)(postId);
  //文章下没有投票
  if (_rel.length <= 0) {
    return callback(null, null);
  }
  let pollDetail = _rel[0],
    pollId = pollDetail.pollId,
    rel = {};
  rel.title = pollDetail.question;
  rel.pollId = pollDetail.pollId;
  //判断有没有过期
  if (new Date(pollDetail.endAt).getTime() < Date.now()) {
    rel.status = '已过期';
    rel.voteRel = await util.promiseify(model.getPollRelByPollId)(pollId);
  } else {
    rel.status = '未过期';
  }

  //获取选项
  let choiceRel = await util.promiseify(model.getPollChoiceByPollId)(pollId);
  rel.choiceArr = choiceRel;

  return callback(null, rel);
});

exports.add = (question, endAt, postId, choice, callback) => {
  var tmp = util.firstKeyOfNull(
    {
      question,
      endAt,
      postId,
      choice,
    },
    ['question', 'endAt', 'postId', 'choice'],
  );
  if (tmp != null) {
    return callback({
      errNo: errCode.LESS_OF_DATA_ERROR,
      extraMsgs: tmp,
    });
  }
  model.add({question, endAt, postId}, choice, callback);
};
